//$URL: http://dasding.googlecode.com/svn/trunk/api/src/main/java/de/piratech/dasding/security/CustomResourceFilterFactory.java $
//$Id: CustomResourceFilterFactory.java 88 2012-11-05 22:54:19Z amuthmann@gmail.com $
package de.piratech.dasding.security;

import de.piratech.dasding.security.contextfilter.UsernameCheckContextFilter;
import de.piratech.dasding.security.annotations.RequireUserIdCheck;
import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.ext.Provider;

import org.springframework.stereotype.Component;

import com.sun.jersey.api.model.AbstractMethod;
import com.sun.jersey.spi.container.ResourceFilter;
import com.sun.jersey.spi.container.ResourceFilterFactory;
import de.piratech.dasding.security.annotations.RequireUserRole;
import de.piratech.dasding.security.contextfilter.UserRoleContextFilter;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;

/**
 * Implementation of ResourceFilterFactory used to add required ContextFilter to the filterchain
 *
 * @author deveth0
 */
@Component // let spring manage the lifecycle
@Provider  // register as jersey's provider
public class CustomResourceFilterFactory implements ResourceFilterFactory {

  @Context
  private UriInfo mUriInfo;

  @Override
  public List<ResourceFilter> create(AbstractMethod pAbstractMethod) {
    List<ResourceFilter> filters = new ArrayList<ResourceFilter>();
    if (pAbstractMethod.isAnnotationPresent(RequireUserIdCheck.class)
            || pAbstractMethod.getResource().isAnnotationPresent(RequireUserIdCheck.class)) {
      filters.add(new UsernameCheckContextFilter(mUriInfo));
    }
    if (pAbstractMethod.isAnnotationPresent(RequireUserRole.class)) {
      filters.add(new UserRoleContextFilter(pAbstractMethod.getAnnotation(RequireUserRole.class).roles()));
    }
    if(pAbstractMethod.getResource().isAnnotationPresent(RequireUserRole.class)){
      filters.add(new UserRoleContextFilter(pAbstractMethod.getResource().getAnnotation(RequireUserRole.class).roles()));
    }
    return filters;
  }
}
